<?php
namespace addons\mall\controller;

use app\common\model\mall\user\Favorite as M;
use think\Db;
/**
 * 收藏控制器
 */
class Favorite extends Base{

	/**
	 * 关注的商品列表
	 */
	public function Wishlist(){
        $user_id = (int)cookie('uid');
        $pagesize = $this->request->get('pagesize',10);
        if ($this->request->isAjax()) {
            $goods = Db::name("mall_user_favorite")->alias('f')
                ->join('__MALL_GOODS_GOODS__ g','g.id = f.target','left')
                ->join('__MALL_SHOP_SHOP__ s','s.id = g.shop_id','left')
                ->field('f.id,f.target goods_id,g.goodsname,g.goodsimg,g.shopprice,g.shop_id,s.name')
                ->where(['f.user_id'=> $user_id,'type'=> 'goods'])
                ->order('f.id desc')
                ->select();

            $result = array("msg" => "成功","code"=>1, "data"=>["list" => $goods]);
            return json($result);
        }
        return $this->fetch("/cart/wishlist");
	}
	
	/**
	 * 取消关注
	 */
	public function cancel(){
        $id = input("param.id");
        $type = input("param.type");
        $user_id = (int)cookie('uid');
        $ids = explode(',',$id);

        if(empty($ids)) $this->error("取消失败");
        $rs = M::where(['id'=>['in',$ids],'type'=>$type,'user_id'=>$user_id])->delete();
        if(false !== $rs){
            $this->success("取消成功");
        }else{
            $this->error("取消失败");
        }
	}

	/**
	 * 增加关注
	 */
	public function add(){
        $id = input("param.id/d");
        $type = input("param.type");
        $user_id = (int)cookie('uid');
        if($user_id==0)$this->error('关注失败，请先登录');
        //判断记录是否存在
        $isFind = false;
        if($type=='goods'){
            $c = Db::name('mall_goods_goods')->where(['goodsstatus'=>1,'status'=>['in',["sale","warn"]],'id'=>$id])->count();
            $isFind = ($c>0);
        }
        elseif($type=='shop'){
            $c = Db::name('mall_shop_shop')->where(['state'=>1,'status'=>'normal','id'=>$id])->count();
            $isFind = ($c>0);
        }
        if(!$isFind) $this->error("关注失败，无效的关注对象");
        $data = [];
        $data['user_id'] = $user_id;
        $data['type'] = $type;
        $data['target'] = $id;
        //判断是否已关注
        $m = new M;
        $rc = $m->where($data)->count();
        if($rc>0) $this->success("关注成功");
        //$data['createtime'] = date('Y-m-d H:i:s');
        try{
            $rs = $m->save($data);
            if(false !== $rs){
                $this->success("关注成功",null, ['fId'=>$m->id]);
            }else{
                $this->error($this->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
	}

}
